<template>
  <div class="demo-content">
    <section class="demo-text">
      <h1>属性设计</h1>
      <el-button-group>
        <el-button @click="del">删除</el-button>
        <el-button
          v-for="(item,index) in drawtypelist"
          :type="item.type"
          @click="draw(item.type)"
          :class="drawtype==item.type?'shActive':''"
          :key="item.type"
        >{{item.name}}</el-button>
        <el-button @click="downloadfile">保存文件</el-button>
      </el-button-group>
      <div style="position:relative;margin:30px">
        <canvas id="canvas" width="1600" height="700" ref="canvas"></canvas>
      </div>
      <p style="text-align:right;padding-right:60px">@王睿杰 2019.4.24</p>
    </section>
  </div>
</template>
<script>
/**
 * write a component's description
 * 包含了绘制插件和工具栏，等等的编辑器组件
 */
import BaseCanvas from "@/js/staticCanvas.js";
import base from "@/js/companyBase.js";
import rluer from "@/js/rluer.js";
import history from "@/js/sc_history.js";
import interactive from "@/js/fabric.interactive.js";
import Cstyle from "./cstyle";
import { events, exportlist } from "./setting";
function evaltest(string) {
  try {
    return eval(string);
  } catch (e) {
    return e.message;
  }
}
export default {
  components: {
    Cstyle
  },
  /**
   * @description 返回的数据
   * @returns {Object}
   */
  data() {
    return {
      drawtypelist: [
        {
          name: "点",
          type: "point"
        },
        {
          name: "线",
          type: "line"
        }
      ], //绘制类型列表
      activeObjlist: "objlist", //左侧tab切换
      editable: true, //是否编辑状态
      canvas: null, //画布
      _clipboard: null, //粘贴板
      mouseevent: null, //复制粘贴实践
      refresh: true, //刷新控制
      colorList: {
        //颜色控制器列表
        fill: "#ff0000",
        stroke: "#002546",
        strokeWidth: 1
      }, //树状结果默认显示
      defaultProps: {
        name: "name",
        children: "_objects"
      },
      events, //监听的事件
      activeName: "brush", //右侧列表
      _history: null, //历史
      _start: null, //绘制开始坐标（已弃用）
      isDrawingMode: true, //是否在绘制模式（已弃用）
      _drawingobj: null, //当前正在绘制的元素对象（已弃用）
      attForm: {
        attribute: base,
        style: {}
      },
      interactive: null, //交互器
      activeobj: null, //当前活跃的元素
      in1: null, //绘制器的交互区
      stylelist: [{ name: "设备名称", key: "label", type: "String" }], //样式列表
      cmdlist: [],
      cmdinput: ""
    };
  },
  methods: {
    zoomToPoint() {
      this.canvas.zoomToPoint({ x: 0, y: 0 }, 5);
      this.canvas.fire("ruler", {});
    },
    /**
     * @description 选中绘制元素，添加为热点，删除热点
     */
    addhotspot() {
      this.activeobj &&
        this.activeobj.set("hotspot", true) &&
        this.activeobj.set("opacity", "0.3");
      this.canvas.renderAll();
      this.activeobj &&
        this.$notify({
          title: "提示",
          message: "添加热点成功",
          duration: 2000,
          position: "top-left"
        });
    },
    clearhotspot() {
      this.activeobj &&
        this.activeobj.set("hotspot", false) &&
        this.activeobj.set("opacity", "1");
      this.canvas.renderAll();
      this.activeobj &&
        this.$notify({
          title: "提示",
          message: "清除热点成功",
          duration: 2000,
          position: "top-left"
        });
    },
    loadfile(name) {
      this.SaveFile();
      if (maplist[name]) {
        let canvas = this.canvas;
        canvas.loadFromJSON(maplist[name], canvas.renderAll.bind(canvas));
        loadTuopu.call(canvas, maplist[name].tuopu);
        this.mapname = name;
        this.reload();
      }
    },
    SaveFile() {
      this.mapname = this.mapname || "test";
      let name = this.mapname;
      let data = this.canvas.toJSON(exportlist);
      data.name = name;
      data.tuopu = saveTuopu(this.canvas);
      maplist[name] = data;
      this.reload();
      data = decoration(JSON.stringify(data, null, "\t"), name);
      return data;
    },
    downloadfile() {
      let data = this.SaveFile();
      SaveFile(new Blob([data]), this.mapname + ".js");
    },
    /**
     * 删除
     */
    /**
     * @description
     */
    del() {
      let obj = this.canvas.getActiveObject();
      if (!obj) {
        return;
      }
      let _this = this;
      if (obj && obj._objects) {
        obj._objects.forEach(element => {
          _this.canvas.remove(element);
          this.canvas.fire("remove", { target: element });
        });
      } else {
        this.canvas.remove(obj);
        this.canvas.fire("remove", { target: obj });
      }
    },
    /**
     * 绘制，选择绘制类型
     */
    /**
     * @description
     * @param {any} type
     */
    draw(type) {
      this.canvas.chooseDrawtype(type);
    },
    /**
     * 开始编辑
     */
    /**
     * @description
     */
    drawstart() {
      this.isDrawingMode = true;
      this.canvas.draweditable(true);
      this.editable = true;
    },
    /**
     * 结束编辑
     */
    /**
     * @description
     */
    drawend() {
      this.isDrawingMode = false;
      this.canvas.draweditable(false);
      this.editable = false;
    },
    /**
     * 刷新dom
     */
    /**
     * @description
     */
    reload: function() {
      this.refresh = false;
      this.refresh = true;
    },
    /**
     * @description
     */
    clear() {
      this._clipboard = null;
      this.mouseevent = null;
    },
    /**
     * @description
     */
    Copy() {
      // clone what are you copying since you
      // may want copy and paste on different moment.
      // and you do not want the changes happened
      // later to reflect on the copy.
      let _this = this;
      _this.mouseevent = null;
      this.canvas.getActiveObject() &&
        this.canvas.getActiveObject().clone(function(cloned) {
          _this._clipboard = cloned;
          _this.$notify({
            title: "提示",
            message: "复制成功",
            duration: 2000,
            position: "top-left"
          });
        });
    },
    Paste(e) {
      let _this = this;
      let canvas = _this.canvas;
      let _clipboard = _this._clipboard;
      if (!_this._clipboard) {
        _this.$notify({
          title: "提示",
          message: "需要先进行复制才能粘贴",
          duration: 2000,
          position: "top-left"
        });
        return;
      }
      let pointer = e.pointer || {};
      // clone again, so you can do multiple copies.
      _this._clipboard.clone(function(clonedObj) {
        canvas.discardActiveObject();
        clonedObj.set({
          left: pointer.x || clonedObj.left + 10,
          top: pointer.y || clonedObj.top + 10,
          evented: true
        });
        if (clonedObj.type === "activeSelection") {
          // active selection needs a reference to the canvas.
          clonedObj.canvas = canvas;
          clonedObj.forEachObject(function(obj) {
            canvas.add(obj);
          });
          // this should solve the unselectability
          clonedObj.setCoords();
        } else {
          canvas.add(clonedObj);
        }
        // _clipboard.top += 10;
        // _clipboard.left += 10;
        canvas.setActiveObject(clonedObj);
        canvas.requestRenderAll();
      });
    }
  },
  computed: {
    /**
     * 返回绘制类型
     */
    /**
     * @description
     * @returns {any}
     */
    drawtype() {
      if (this.canvas) {
        return this.canvas.getdrawtype();
      } else {
        return "";
      }
    },
    /**
     * 返回元素列表
     */
    /**
     * @description
     * @returns {any}
     */
    objlist() {
      return this.canvas && this.canvas._objects;
    },
    /**
     * @description
     * @returns {any}
     */
    objTojson() {
      return this.canvas && this.canvas.toDatalessJSON(exportlist, true);
    }
  },
  watch: {
    /**
     * @description
     * @param {any} newval
     * @param {any} oldval
     */
    objlist(newval, oldval) {
      this.reload();
    }
  },
  /**
   * 实例挂载后执行的事件
   */
  mounted() {
    let that = this;
    /**
     * 1.生成画布
     * 2.将交互器赋值给data，以便后续操作
     * 3.设置绘制类型为矩形
     * 4.设置监听事件，监听元素改变
     */
    this.$nextTick(() => {
      let canvas;

      canvas = this.canvas = new BaseCanvas("canvas");
      window.canvas1 = canvas;
      canvas.init();
      canvas.addRluer();
      this._history = canvas.getHistory();
      this.interactive = canvas.getInteractor();
      this.in1 = canvas.getMaskInteractor();
      this.events.map(item => {
        canvas.on(item, function(e) {
          that.activeobj = null;
          that.activeobj = e.target || canvas.getActiveObject();
        });
      });
      canvas.on("mouse:move", function(e) {
        that.mouseevent = e;
      });
    });
  },
  /**
   * @description
   */
  distoryed() {
    window.removeEventListener("keydown");
  }
};
</script>

